package org.cvcsc.weproject.service;

import org.cvcsc.weproject.domain.Clazz;
import org.cvcsc.weproject.domain.CourseSchedule;
import org.cvcsc.weproject.repository.ClazzRepository;
import org.cvcsc.weproject.repository.CourseScheduleRepository;
import org.cvcsc.weproject.repository.Finder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class CourseScheduleService {

    @Autowired
    private CourseScheduleRepository courseScheduleRepository;

    @Autowired
    private Finder<Clazz, Long> clazzRepository;

    /**
     * 创建新的课程安排。
     *
     * @param courseSchedules 新的课程安排对象列表
     * @return 创建的课程安排对象列表
     * @throws IllegalArgumentException 如果班级不存在
     */
    public List<Long> createCourseSchedules(List<CourseScheduleUpdateCommand> commands) {
        List<CourseSchedule> courseSchedules = commands.stream()
                .map(command -> {
                    Long clazzId = command.getClazzId();
                    Clazz clazz = clazzRepository.findById(clazzId)
                            .orElseThrow(() -> new IllegalArgumentException("班级ID " + clazzId + " 不存在"));

                    // 直接在这里创建 CourseSchedule
                    return CourseSchedule.instanceOf(
                            clazz,
                            command.getCourseName(),
                            command.getCourseScheduleTime()
                    );
                })
                .collect(Collectors.toList());
        return courseScheduleRepository.saveAll(courseSchedules).stream().map(CourseSchedule::getId).collect(Collectors.toList());
    }

    /**
     * 更新现有的课程安排。
     *
     * @param id             课程安排的ID
     * @param courseSchedule 更新后的课程安排对象
     */
    public void updateCourseSchedule(Long id, CourseScheduleUpdateCommand command) {
        final CourseSchedule existingCourseSchedule = courseScheduleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("课程安排不存在"));
        Clazz clazz = clazzRepository.findById(command.getClazzId()).orElseThrow(() -> new RuntimeException("班级不存在"));
        existingCourseSchedule.updateWith(clazz, command.getCourseName(), command.getCourseScheduleTime());
        courseScheduleRepository.save(existingCourseSchedule);
    }

    /**
     * 删除指定ID的课程安排。
     *
     * @param id 课程安排的ID
     * @return 删除结果，如果删除成功则返回true，否则返回false
     */
    public boolean deleteCourseSchedule(Long id) {
        Optional<CourseSchedule> courseSchedule = courseScheduleRepository.findById(id);
        if (courseSchedule.isPresent()) {
            courseScheduleRepository.deleteById(id);
            return true;
        } else {
            return false;
        }
    }

    public void deleteCourseScheduleAll() {
        courseScheduleRepository.deleteAll();
    }

}
